package com.project.srtp.secure.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.srtp.secure.dao.entity.PartyDO;
import com.project.srtp.secure.dao.mapper.PartyMapper;
import com.project.srtp.secure.service.PartyService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 曹行阳
 * @version 0.1
 * @date 2025/6/16 19:28
 */
@Service
public class PartyServiceImpl extends ServiceImpl<PartyMapper, PartyDO> implements PartyService {
    @Override
    @Transactional
    public void createSingleSession(PartyDO partyDO) {
        int insert = baseMapper.insert(partyDO);
        if (insert == 0) {
            throw new RuntimeException("插入失败");
        }
    }

    @Override
    public Optional<String> findExistingPartyId(String fromUserId, String toUserId) {
        List<PartyDO> parties1 = baseMapper.selectList(Wrappers.lambdaQuery(PartyDO.class)
                .eq(PartyDO::getUserId, fromUserId));
        List<PartyDO> parties2 = baseMapper.selectList(Wrappers.lambdaQuery(PartyDO.class)
                .eq(PartyDO::getUserId, toUserId));
        Set<String> partyIds1 = parties1.stream().map(PartyDO::getPartyId).collect(Collectors.toSet());
        Set<String> partyIds2 = parties2.stream().map(PartyDO::getPartyId).collect(Collectors.toSet());
        partyIds1.retainAll(partyIds2);
        return partyIds1.stream().findFirst();
    }
}
